//
package rmhc.api.vk
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.Event;
	
	import rmhc.api.dataflow.WallPostInfo;
	import rmhc.api.tasks.IWallPost;
	import rmhc.gui.SupplyFunctions;
	import rmhc.gui.customTrace;
	import rmhc.server.FileUploader;
	
	public class WallSavePost extends VkApiTask implements IWallPost
	{
		private var post:WallPostInfo;
		private var ready:Boolean = false;
		private var upl:FileUploader;
		private var save:VkApiTask;
		
		public function WallSavePost(wrapper:VkApi,post:WallPostInfo)
		{
			customTrace("WallSavePost:WallSavePost:" );
			/*var wall_id:String;
			if(post.wallId){
				wall_id = post.wallId;
			}else {
				wall_id = wrapper.getUID();
			}*/
			//var message:String = post.descr;
			super( wrapper , null );
			if (!post.thumbPng)
			{
				throw(new Error("Error in WallSavePost:run. (!post.thumbPng) == true, а значит в посте нет корректных данных"));
			}
			this.post = post;
		}
		public function getPostId():String {
			return post.postId;
		}
		override public function run():void 
		{
			upl = new FileUploader( vkapi.getWallUploadUrl() );
			upl.addFile( "photo" , "photo.png" , post.thumbPng , "image/png" );
			upl.addEventListener( Event.COMPLETE , upl_complete);
			upl.load(null);
		}
		override public function parseData(result:Object):void
		{
			throw new Error( "nope!" );
			/*customTrace("WallSavePost:parseData:" +SupplyFunctions.objectToString(result));
			post.postId = result.pid;
			post.hash = result.hash;
			vkapi.saveWallPost(post.hash);
			customTrace("WallSavePost:parseData: (wrapper as VkApi).saveWallPost(post_hash);" );
			onComplete();*/
		}
		private function upl_complete(e:Event):void 
		{
			ready = true;
			var resp:Object = JSON.decode( upl.data );
			
			var params:Object = { "wall_id" : post.wallId, "message" : post.descr , "post_id" : post.postId }
			params.server = resp.server;
			params.photo = resp.photo;
			params.hash = resp.hash;
			
			save = new VkApiTask( wrapper, "wall.savePost" , params );
			save.addEventListener(Event.COMPLETE , onSaved );
			vkapi.addTask(save);
			save.run();
		}
		protected function onSaved( e:Event ):void
		{
			var raw:Object = save.getRawData();
			vkapi.saveWallPost( raw.post_hash );
			onComplete();
		}
		override public function getMethod():String 
		{
			if (!ready)
				return null;
			return super.getMethod();
		}		

		/*public function getPostHash():String {
			return post.hash;
		}*/
		
	}
}